<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { type IconConfig } from "@/types";
import { store } from "@/pinia";

/**
 * 图标参数
 */
const props = defineProps<{
  config: IconConfig; // 配置
}>();

const iconClassList = ref([
  "icon",
  `icon-size-${props.config.size}`,
  `icon-type-${props.config.type || "white"}`,
]); // 图标类数组
const iconClass = computed(() => iconClassList.value.join(" ")); // 图标类名
const { idGeneratorStore } = store(); // 全局ID生成器
const iconId = ref(idGeneratorStore.incr("icon")); // 图标元素ID

const iconName = ref(`#icon-${props.config.name}`); // 图标名称

/**
 * 获取元素
 */
const currentElement = (): HTMLElement => {
  return document.querySelector(`#${iconId.value}`)!;
};

onMounted(() => {
  if (props.config.rotating) {
    iconClassList.value.push("rotating");
  }
  if (props.config.size) {
    currentElement().style.fontSize = `var(--${props.config.size}-text)`;
  } else if (props.config.customSize) {
    currentElement().style.fontSize = props.config.customSize;
  }
});
</script>

<template>
  <svg :id="iconId" :class="iconClass">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<style lang="scss" scoped>
.icon {
  fill: currentColor;
  overflow: hidden;
}

.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
